import React, { useEffect, useRef, useState } from 'react'
import axios from 'axios';
axios.defaults.baseURL = 'http://localhost:3500';
export default function PaiZhao() {
    const cameraVideoRef = useRef(null);
    const cameraCanvasRef = useRef(null);
    const [Img, setImg] = useState("")
    useEffect(() => {
        openMedia() //打开摄像头
    }, [])

    function successFunc(mediaStream) {
        const video = cameraVideoRef.current;
        // const video = document.getElementById('cameraVideo') as HTMLVideoElement;
        // 旧的浏览器可能没有srcObject
        if ('srcObject' in video) {
            video.srcObject = mediaStream;
        }
        video.onloadedmetadata = () => {
            video.play();
        };
    }

    function errorFunc(err) {
        console.log(`${err.name}: ${err.message}`);
        // always check for errors at the end.
    }

    // 启动摄像头
    const openMedia = () => { // 打开摄像头
        const opt = {
            audio: false,
            video: {
                width: 960,
                height: 720
            }
        };
        navigator.mediaDevices.getUserMedia(opt).then(successFunc).catch(errorFunc);
    };
    // 关闭摄像头
    const closeMedia = () => {
        const video = cameraVideoRef.current;
        const stream = video.srcObject;
        if ('getTracks' in stream) {
            const tracks = stream.getTracks();
            tracks.forEach(track => {
                track.stop();
            });
        }
    };

    const getImg = () => { // 获取图片资源
        const video = cameraVideoRef.current;
        const canvas = cameraCanvasRef.current;
        if (canvas == null) {
            return;
        }
        const ctx = canvas.getContext('2d');
        ctx.drawImage(video, 0, 0, 300, 150); // 把视频中的一帧在canvas画布里面绘制出来
        const imgStr = canvas.toDataURL(); // 将图片资源转成字符串
        const base64Img = imgStr.split(';base64,').pop(); // 将图片资源转成base64格式
        axios.post("/face",{imageData:base64Img}).then(res=>{
            if(res.data.code==200){
                alert("识别成功欢迎登录"+res.data.user.username)
                window.location.href=`/app/shou?_id=${res.data.user._id}`
            }else{
                alert("识别失败")

            }
        })
        const imgData = {
            base64Img
        };
        closeMedia(); // 获取到图片之后可以自动关闭摄像头
        return imgData;
    };


    const saveImg = () => { // 保存到本地
        const data = getImg();
        console.log(data);
        setImg('data:image/png;base64,' + data.base64Img)
    };
    return (
        <div style={{textAlign:"center"}}>
            {
                Img?<img id="imgTag" style={{width:"300px",height:"300px",borderRadius:"50%"}} src={Img} alt="imgTag" />:<div><div className='PaiZhao'>
                <video

                    id="cameraVideo"
                    ref={cameraVideoRef}
                    className='PaiZhao_video'
                    style={{
                      width: '200px', height: '200px',borderRadius:"50%"
                    }}
                />
            </div>
            <div className='PaiZhao'>
                <canvas
                    id="cameraCanvas"
                    ref={cameraCanvasRef}
                    className='PaiZhao_canvas'
                />
            </div>
            </div>
            }


            <button onClick={() => {
                saveImg()
                closeMedia()
            }}>保存</button>
        </div>
    )
}
